<template>
  <el-dialog
    v-model="dialogVisible"
    title="选择JSA模板"
    width="800px"
    @close="handleClose"
  >
    <div class="template-select">
      <!-- 筛选条件 -->
      <div class="filter-section">
        <el-form :model="filters" inline>
          <el-form-item label="作业类型">
            <el-select v-model="filters.jobType" placeholder="全部类型" clearable>
              <el-option label="全部" value="" />
              <el-option
                v-for="jobType in templateStore.getJobTypes"
                :key="jobType"
                :label="jobType"
                :value="jobType"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="模板名称">
            <el-input
              v-model="filters.keyword"
              placeholder="搜索模板名称"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 模板列表 -->
      <div class="template-list">
        <el-table
          :data="filteredTemplates"
          @row-click="handleRowClick"
          highlight-current-row
        >
          <el-table-column prop="name" label="模板名称" width="200" />
          <el-table-column prop="jobType" label="作业类型" width="120">
            <template #default="{ row }">
              <el-tag :type="getWorkTypeTagType(row.jobType)">
                {{ getWorkTypeLabel(row.jobType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" />
          <el-table-column label="步骤数" width="100" align="center">
            <template #default="{ row }">
              <el-tag size="small">{{ row.workSteps.length }} 步</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="160" />
        </el-table>
      </div>
      
      <!-- 模板预览 -->
      <div v-if="selectedTemplate" class="template-preview">
        <h4>模板预览：{{ selectedTemplate.name }}</h4>
        <JSATemplateTable :template="selectedTemplate" />
      </div>
    </div>
    
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button 
        type="primary" 
        @click="handleConfirm" 
        :disabled="!selectedTemplate"
      >
        选择模板
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useJSATemplateStore } from '@/stores/jsTemplate'
import JSATemplateTable from './JSATemplateTable.vue'
import type { JSATemplate } from '@/types'

interface Props {
  modelValue: boolean
  workType?: string
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'confirm', template: JSATemplate): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const templateStore = useJSATemplateStore()

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const filters = reactive({
  jobType: '',
  keyword: ''
})

const selectedTemplate = ref<JSATemplate | null>(null)

// 获取模板数据
const templateData = computed(() => templateStore.getAllTemplates())

// 过滤后的模板列表
const filteredTemplates = computed(() => {
  let result = templateData.value

  // 根据作业类型过滤
  if (props.workType) {
    result = result.filter(template => template.jobType === props.workType)
  }

  // 根据筛选条件过滤
  if (filters.jobType) {
    result = result.filter(template => template.jobType === filters.jobType)
  }

  if (filters.keyword) {
    const keyword = filters.keyword.toLowerCase()
    result = result.filter(template => 
      template.name.toLowerCase().includes(keyword) ||
      (template.description && template.description.toLowerCase().includes(keyword))
    )
  }

  return result
})

// 获取作业类型标签类型
const getWorkTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    '高空作业': 'warning',
    '电工作业': 'primary',
    '动火作业': 'danger',
    '受限空间': 'info',
    '起重作业': 'success'
  }
  return typeMap[type] || 'info'
}

// 获取作业类型标签
const getWorkTypeLabel = (type: string) => {
  return type
}


// 处理行点击
const handleRowClick = (row: JSATemplate) => {
  selectedTemplate.value = row
}

// 确认选择
const handleConfirm = () => {
  if (!selectedTemplate.value) {
    ElMessage.warning('请选择一个模板')
    return
  }

  emit('confirm', selectedTemplate.value)
  handleClose()
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  selectedTemplate.value = null
  filters.jobType = ''
  filters.keyword = ''
}

// 监听对话框显示状态
watch(dialogVisible, (visible) => {
  if (!visible) {
    handleClose()
  }
})
</script>

<style lang="scss" scoped>
.template-select {
  .filter-section {
    margin-bottom: 20px;
    padding: 16px;
    background: #f8f9fa;
    border-radius: 4px;
  }
  
  .template-list {
    margin-bottom: 20px;
  }
  
  .template-preview {
    h4 {
      color: #333;
      margin-bottom: 12px;
    }
  }
}
</style>

